#include "747engine.h"

namespace Engine
{
		bool Engine::init()
		{
			this->windowTitle = "747Engine version"+this->getVersion();
			this->wHeight = 600;
			this->wWidth = 800;
			this->isFullscreen = false;
			this->ups = 60;
			this->fps = 60;
			preInit();

			textureManager = new TextureManager;
			entityManager = new EntityManager;
			stateManager = new StateManager;

			postInit();

			return true;
		}
		void Engine::setSettings(std::string fwindowTitle, int fwHeight, int fwWidth, bool fisFullscreen, int fups, int ffps)
		{
			this->windowTitle = fwindowTitle;
			this->wHeight = fwHeight;
			this->wWidth = fwWidth;
			this->isFullscreen = fisFullscreen;
			this->ups = fups;
			this->fps = ffps;
		}
		void Engine::run()
		{
			window.Create(sf::VideoMode(this->wWidth, this->wHeight),this->windowTitle);
		}

		void Engine::close()
		{
			delete textureManager;
			delete entityManager;
			delete fontManager;
			delete stateManager;
			std::list<Entity*>::iterator iter = entityManager->getEntities()->begin();
			while (iter != entityManager->getEntities()->end()) 
			{
				delete entityManager->getEntities()->back();
				++iter;
			}

			running = false;
		}

		void Engine::gameLoop()
		{
			while(this->getRunning())
			{
				sf::Event Event;
				window.PollEvent(Event);
				eventHandler(Event);
			}

		}

		void Engine::eventHandler(sf::Event Event)
		{
			if(Event.Type == sf::Event::Closed)
				close();
			else if(Event.Type == sf::Event::KeyPressed)
				onKeyPress(Event.Key.Code);
			else if(Event.Type == sf::Event::KeyReleased)
				onKeyRelease(Event.Key.Code);

			stateManager->getStates()->back()->HandleEvent(Event);
		}

		void Engine::log(std::string message, int type)
		{
			std::ofstream file;
			file.open("log.txt");
			file<<type<<": "<<message<<std::endl;
			file.close();
			std::cout<<type<<": "<<message<<std::endl;
		}

		void Engine::update()
		{
			if((1.0f/ups) < this->updateTimer.GetElapsedTime().AsSeconds())
			{
				game_update();
				this->updateTimer.Restart();
				stateManager->getStates()->back()->Update();
			}
		}
		void Engine::draw()
		{
			if((1.0f/fps) < this->drawTimer.GetElapsedTime().AsSeconds())
			{
				game_draw();
				this->drawTimer.Restart();
				stateManager->getStates()->back()->Draw(window);
			}
		}
}